<?php

namespace app\api\logic;
use  app\api\logic\BasicLogic;
use app\common\library\RedissLock;
use app\common\service\CommonExportCsvTaskLogService;
use app\common\service\CommonSystemImportService;
use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Cache;
use think\facade\Db;

class TeamLogic extends BasicLogic
{

    const Report_Page_token           = 'report_page_token::';
    const Report_Cookie               = 'Report_Cookie::';
    const Csrf_Token_pc               = 'csrf_token_pc::';

    const App_Analytics_Token_Shopify = "app_analytics_token_shopify::";
    const App_Analytics_Error         = "app_analytics_error::";




    /**
     * @desc  spu超过180天开发变为历史生产方法
     * @author xx
     * @date 2024-10-30
     */
    public function upDevelopTypeProduce(){
           $where   = [];
           $where[] = ['develop_type','in',[2,3]];
           $list    = Db::name('product')->where($where)->field('id,spu,develop_type,published_time')->select();
           $list    = objectToArray($list);
           if($list){
               foreach($list as $v){
                   //推动数据到队列;
                   MqTaskPushLogic::mq_task_push(
                       '',
                       MqQueueName::QUEUE_ORDER_PRODUCT_DEV_QUEUE,
                       $v,
                       false
                   );
               }
           }
    }



    /**
     * @desc  spu超过180天开发变为历史消费方法
     * @author xx
     * @date 2024-10-30
     */
    public function upDevelopTypeConsumer($info){
           $id             = $info['id']??'';
           $published_time = $info['published_time']??'';
           if(!$published_time) return ['msg'=>'刊登时间为空!'];
           $published_time = strtotime($published_time);
           // $published_time+180天 和当前时间对比;
           $update_time = $published_time+86400*180;
           if(time()>$update_time){
                 Db::name('product')->where(['id'=>$id])->update(
                     [
                         'develop_type'=>1
                     ]
                 );
           }
           return  true;
    }



    /**
     * @desc    获取员工花名册信息
     * @author  xx
     * @date    2024-10-30
     */
    public function upEmployeesProduce($params=[]){
        $where        = [];
        $employees_on = Config('Logisticskey.employees_on');
        $where[] = ['open_id','<>',''];
        $where[] = ['employees_status','=',1];
        $where[] = ['id','not in',$employees_on];
        $list    = Db::name('system_admin')->where($where)->field('id,open_id')->select();
        $list    = objectToArray($list);
        if(!$list)    return '暂无数据!';
        foreach($list as $v){
                //推动数据到队列;
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_ORDER_EMPLOY_STATUS_QUEUE,
                    $v,
                    false
                );
            }
          $num = count($list);
          return '员工花名册信息处理数据'.$num.'条';

        }


    /**
     * @desc     更新cookie信息
     * @date     2024-11-07
     * @author   luckyXiong
     */
    public function upCookieInfo($params=[]){
        $page_token = $params['page_token']??'';
        $cookie     = $params['cookie']??'';
        $csrf_token = $params['csrf_token']??'';
        $shop_id    = $params['shop_id']??'17';
        $key_page_token= self::Report_Page_token.$shop_id;
        $key_cookie = self::Report_Page_token.$shop_id;
        $key_token  = self::Csrf_Token_pc.$shop_id;
        Cache::store('redis')->set($key_cookie,$cookie);
        Cache::store('redis')->set($key_page_token,$page_token);
        Cache::store('redis')->set($key_token,$csrf_token);
    }

    /**
     * @desc     更新AnalyticsToken信息
     * @date     2024-11-07
     * @author   luckyXiong
     */
    public function getAnalyticsToken($shop_id=''){
        $key             = self::App_Analytics_Token_Shopify.$shop_id;
        $key_page_token  = self::Report_Page_token.$shop_id;
        $key_csrf_token  = self::Csrf_Token_pc.$shop_id;
        $token           = Cache::store('redis')->get($key);
        $page_token      = Cache::store('redis')->get($key_page_token);
        $cookie          = Cache::store('redis')->get($key_page_token);
        $csrf_token      = Cache::store('redis')->get($key_csrf_token);
        if(empty($token)){
            $url             = Config('Logisticskey.shopify.get_analytics_token');
            $client_context  = [
                   "client_context"=>[
                       "page_view_token"=>$page_token,
                       "client_route_handle"=>"analytics:reports:id",
                       "client_pathname"=>"/store/vfaja/analytics/reports/sessions_by_landing_page",
                       "client_normalized_pathname"=>"/store/:storeHandle/analytics/reports/:id"
                   ],
            ];
            $data            = [
                "query"             => "query MerchantAnalyticsApiToken {  shop {    id   merchantAnalyticsApiToken    __typename }}",
                "operationName"     =>"MerchantAnalyticsApiToken",
                "operationType"     => "query",
                ];

            $response = HttpUtil::tokenPostUrl($url, $data,$cookie,$csrf_token);
            if(isset($response['data']['shop']['merchantAnalyticsApiToken']) && $response['data']['shop']['merchantAnalyticsApiToken']){
                $token  = $response['data']['shop']['merchantAnalyticsApiToken'];
                $expire = 300; // 设置5分钟
                Cache::store('redis')->set($key, $token,$expire-6);
            }else{
                //飞书消息推送需要更新 cookie;
                $open_id  = 'ou_f7192fb282ef3b6cbb04ec48bb1f803a';
                $msg      = "您的cookie信息已过期,请手动更新";
                $msg_info = [
                    'message' => $msg,
                    'open_id' => $open_id,
                ];
              //  (new FeiShuMessageLogic())->send_message($msg_info);
            }
        }
        return  $token;
    }


    /**
     * @desc     获取登陆页面访问量数据
     * @date     2024-11-07
     * @author   luckyXiong
     */
    public function getVisitList(){
           $shop_ids = Config('Logisticskey.report_shops');
           foreach($shop_ids as $v){
               // 队列处理
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_ORDER_PAGE_VISIT_QUEUE,
                   [
                       'shop_id' =>$v
                   ],
                   false
               );
           }
    }




    /**
     * @desc     获取登陆页面访问量数据
     * @date     2024-11-07
     * @author   luckyXiong
     */
    public function getVisitListDetail($message){
          $shop_id           = $message['shop_id']??'';
          $token             = self::getAnalyticsToken($shop_id);
          if(!$token)        return  'token数据已经过期!';
          $url               = Config('Logisticskey.shopify.get_visit_list');
          $query             = 'FROM sessions
                                SHOW online_store_visitors, sessions, sessions_with_cart_additions,
                                sessions_that_reached_checkout
                                WHERE landing_page_path IS NOT NULL
                                GROUP BY landing_page_type, landing_page_path WITH TOTALS
                                SINCE startOfDay(-7d) UNTIL today
                                ORDER BY sessions DESC
                                LIMIT 1000
                                VISUALIZE sessions, online_store_visitors, sessions_with_cart_additions,
                                sessions_that_reached_checkout TYPE list_with_dimension_values';
          $data = [
              'query' =>$query,
          ];
          $response = HttpUtil::postFeiShu($url,$token,$data);
          $list = $response['table_data']['rows']??[];
          $arr  = [];

         if($list){
             //每次取当天最新的数据;
             Db::name('order_page_visits')->where(['shop_id'=>$shop_id])->delete();
             foreach($list as $v){
                 $page_path = $v['values'][1]['data']['Text']??'';
                 //获取运营维护信息;
                 $admin_info = Db::name('order_page_visits_admin')->where(['shop_id'=>$shop_id,'page_path'=>$page_path])->find();
                 //获取产品信息
                 if(isset($v['0']) && $v['0']=='Product'){
                     $spu    = Db::name('order_page_visits_product')->where(['shop_id'=>$shop_id,'page_path'=>$page_path])->value('spu');
                 }else{
                     $spu    = $admin_info['spu']??'';
                 }

                 $user_id   = $admin_info['admin_id']??'';
                     $temp = [
                         'shop_id'            =>$shop_id,
                         'page_type'          =>$v['values'][0]['data']['Text']??'',
                         'page_path'          =>$v['values'][1]['data']['Text']??'',
                         'online_store_visitors'     =>$v['values'][2]['data']['Int64']??'',
                         'total_sessions'     =>$v['values'][3]['data']['Int64']??'',
                         'total_carts'        =>$v['values'][4]['data']['Int64']??'',
                         'total_checkouts'    =>$v['values'][5]['data']['Int64']??'',
                         'online_visitors'       =>$v['values'][6]['data']['Int64']??'',
                         'sessions__totals'  =>$v['values'][7]['data']['Int64']??'',
                         'sessions_with_cart_additions'   =>$v['values'][8]['data']['Int64']??'',
                         'sessions_that_reached_checkout'=>$v['values'][9]['data']['Int64']??'',
                         'admin_id'           =>$user_id,
                         'spu'                =>$spu??'',
                         'create_time'        =>date("Y-m-d H:i:s", time()),
                     ];
                 $arr[] = $temp;
             }
             Db::name('order_page_visits')->insertAll($arr);
             $num = count($list);
             return '获取当前列表数据'.$num.'条';
         }else{
             $open_id = 'ou_f7192fb282ef3b6cbb04ec48bb1f803a';
             $msg     = "您的当前列表没有数据，请更新cookie！";
             $msg_info = [
                 'message' => $msg,
                 'open_id' => $open_id,
             ];
            // (new FeiShuMessageLogic())->send_message($msg_info);
         }
         return   true;
    }



    /**
     * @desc     获取历史访问量数据
     * @date     2024-11-06
     * @author   luckyXiong
     */
    public function getHistoryVisit(){
        $shop_ids = Config('Logisticskey.report_shops');
        foreach($shop_ids as $v){
            // 队列处理
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_PAGE_HISTORY_QUEUE,
                [
                    'shop_id' =>$v
                ],
                false
            );
        }
    }



    /**
     * @desc     获取历史访问量数据
     * @date     2024-11-07
     * @author   luckyXiong
     */
    public function getHistoryVisitDetail($message){
        $shop_id           = $message['shop_id']??'';
        $token             = self::getAnalyticsToken($shop_id);
        $url               = Config('Logisticskey.shopify.get_visit_list');
        $query             = 'FROM sessions
                                SHOW online_store_visitors, sessions, sessions_with_cart_additions,
                                sessions_that_reached_checkout
                                WHERE landing_page_path IS NOT NULL
                                GROUP BY landing_page_type, landing_page_path WITH TOTALS
                                SINCE startOfDay(-7d) UNTIL today
                                ORDER BY sessions DESC
                                LIMIT 1000
                                VISUALIZE sessions, online_store_visitors, sessions_with_cart_additions,
                                sessions_that_reached_checkout TYPE list_with_dimension_values';
        $data = [
            'query' =>$query,
        ];
        $response = HttpUtil::postFeiShu($url,$token,$data);
        $list = $response['table_data']['rows']??[];
        $arr  = [];
        if($list){
            foreach($list as $v){
                $page_path = $v['values'][1]['data']['Text']??'';
                //获取运营维护信息;
                $admin_info = Db::name('order_page_visits_admin')->where(['shop_id'=>$shop_id,'page_path'=>$page_path])->find();
                //获取产品信息
                if(isset($v['0']) && $v['0']=='Product'){
                    $spu    = Db::name('order_page_visits_product')->where(['shop_id'=>$shop_id,'page_path'=>$page_path])->value('spu');
                }else{
                    $spu    = $admin_info['spu']??'';
                }

                $user_id   = $admin_info['admin_id']??'';
                $temp = [
                    'shop_id'            =>$shop_id,
                    'page_type'          =>$v['values'][0]['data']['Text']??'',
                    'page_path'          =>$v['values'][1]['data']['Text']??'',
                    'online_store_visitors'     =>$v['values'][2]['data']['Int64']??'',
                    'total_sessions'     =>$v['values'][3]['data']['Int64']??'',
                    'total_carts'        =>$v['values'][4]['data']['Int64']??'',
                    'total_checkouts'    =>$v['values'][5]['data']['Int64']??'',
                    'online_visitors'       =>$v['values'][6]['data']['Int64']??'',
                    'sessions__totals'  =>$v['values'][7]['data']['Int64']??'',
                    'sessions_with_cart_additions'   =>$v['values'][8]['data']['Int64']??'',
                    'sessions_that_reached_checkout'=>$v['values'][9]['data']['Int64']??'',
                    'admin_id'           =>$user_id,
                    'spu'                =>$spu??'',
                    'create_time'        =>date("Y-m-d H:i:s", time()),
                ];
                $arr[] = $temp;
            }
            Db::name('order_page_visits_history')->insertAll($arr);
            $num = count($list);
            return '获取历史列表数据'.$num.'条';
        }else{
            $open_id = 'ou_f7192fb282ef3b6cbb04ec48bb1f803a';
            $msg     = "您的历史列表没有数据，请更新cookie！";
            $msg_info = [
                'message' => $msg,
                'open_id' => $open_id,
            ];
          //  (new FeiShuMessageLogic())->send_message($msg_info);
        }
        return  true;
    }


    /**
     * @desc     获取登陆页面显示访问情况数据
     * @date     2025-03-12
     * @author   luckyXiong
     */
    public function getLoginPath($params=[]){
        $token             = $params['token']??"";
        if(!$token)   return  'token不能为空!';
        $url               = Config('Logisticskey.shopify.sessions_by_path_page');
        $query             = 'FROM sessions SHOW online_store_visitors,sessions,sessions_with_cart_additions,sessions_that_reached_checkout WHERE landing_page_path IS NOT NULL GROUP BY landing_page_type,landing_page_path WITH TOTALS SINCE startOfDay(-7d) UNTIL today ORDER BY sessions DESC LIMIT 1000';
        $data              = [
            'query'  => $query,
        ];
        $response  = HttpUtil::PostUrlShpf($url,$token,$data);
        $response  = json_decode($response,true);
        $list      = $response['table_data']['rows']??[];
        $arr       = [];
        if(!$list)   return  '数据为空!需要更新token!';
        if($list){
            //每次取当天最新的数据;
            Db::execute('TRUNCATE TABLE qu_order_path_visits');
            foreach($list as $v){
                $temp  = [
                    'shop_id'            =>17,
                    'page_type'          =>$v['values']['0']['data']['Text']??'',
                    'page_path'          =>$v['values']['1']['data']['Text']??'',
                    'total_visitors'     =>$v['values']['2']['data']['Int64']??'',
                    'total_sessions'     =>$v['values']['3']['data']['Int64']??'',
                    'total_carts'        =>$v['values']['4']['data']['Int64']??'',
                    'total_checkouts'    =>$v['values']['5']['data']['Int64']??'',
                    'create_time'        =>date("Y-m-d H:i:s", time()),
                ];
                $arr[] = $temp;
            }
            Db::name('order_path_visits')->insertAll($arr);
            Db::name('order_path_visits_history')->insertAll($arr);
            $num = count($list);
            return '获取当前列表数据'.$num.'条';
        }else{
            $open_id = 'ou_f7192fb282ef3b6cbb04ec48bb1f803a';
            $msg     = "您的当前列表没有数据，请更新cookie！";
            $msg_info = [
                'message' => $msg,
                'open_id' => $open_id,
            ];
            // (new FeiShuMessageLogic())->send_message($msg_info);
        }
    }


    public function purchase_suggest_plan(){
        //update 2025-06-14  qu_purchase_suggest_plan，获取最新的;
        Db::execute('TRUNCATE TABLE qu_purchase_suggest_plan');
        $Today = date('Y-m-d', strtotime('-1 day') - timezone());
        $yesterday = date('Y-m-d', strtotime('-7 day') - timezone());
        $midnightToday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($Today . ' 23:59:59');
        $where[]  = ['createtime', '>=', $midnightToday];
        $where[]  = ['createtime', '<=', $endOfYesterday];
        $where[]  = ['is_seel', '<>',1];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $lists = Db::name('order_skuinfo')
            ->field('spu,new_sku as sku')
            ->where($where)
            ->group('new_sku')
            ->select()
            ->toArray();
        //存储sku信息;
        self::add_sku($lists);
    }


    public function add_spu_plan(){
        Db::execute('TRUNCATE TABLE qu_purchase_suggest_plan_spu');
        $Today = date('Y-m-d', strtotime('-1 day') - timezone());
        $yesterday = date('Y-m-d', strtotime('-7 day') - timezone());
        $midnightToday = strtotime($yesterday . ' 00:00:00');
        $endOfYesterday  = strtotime($Today . ' 23:59:59');
        $where[]  = ['createtime', '>=', $midnightToday];
        $where[]  = ['createtime', '<=', $endOfYesterday];
        $where[]  = ['is_seel', '<>',1];
        $where[]  = ['financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        $lists = Db::name('order_skuinfo')
            ->field('spu,new_sku as sku')
            ->where($where)
            ->group('new_sku')
            ->select()
            ->toArray();
        $spus = array_column($lists,'spu');
        $spus = array_values(array_unique($spus));
        //存储spu信息;
        self::add_spu($spus);
    }


    /**
     * @desc    备货建议数量spu
     * @author  luckyXiong
     * @date    2025-07-06
     */
    public function add_spu($info){
           foreach($info as $v){
               //推动数据到队列;
               MqTaskPushLogic::mq_task_push(
                   '',
                   MqQueueName::QUEUE_ORDER_PRODUCT_SPU_QUEUE,
                   [
                       'spu'=>$v
                   ],
                   false
               );
           }
    }


    /**
     * @desc    备货建议数量spu
     * @author  luckyXiong
     * @date    2025-07-06
     */
    public function add_sku($list){
        foreach($list as $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_ORDER_PRODUCT_SKU_PLAN_QUEUE,
                $v,
                false
            );
        }
    }





}